from django.shortcuts import render
from django.http import HttpResponse
from user.models import *
from library.models import *
from operation.models import *
import json
import datetime
import time

def login(request):
    return render(request, 'operation/login.html')

def index(request):
    return render(request, 'operation/index.html')

def welcome(request):
    return render(request, 'operation/welcome.html')

def user_list(request):
    user_list = User.objects.all()
    return render(request, 'operation/user_list.html', {'user_list': user_list, 'user_list_count': len(user_list)})

def user_search(request):
    begin_time = datetime.datetime(2017, 1, 1) if request.GET['begin_time']=="" else datetime.datetime(*tuple(map(int, request.GET['begin_time'].split('-'))))
    end_time = datetime.date.today() if request.GET['end_time']=="" else datetime.datetime(*tuple(map(int, request.GET['end_time'].split('-'))))
    user_name = request.GET['user_name']
    if user_name == "":
        user_list = User.objects.filter(user_about_times__range=(begin_time, end_time))
    else:        
        user_list = User.objects.filter(nickname__icontains=user_name,
                                            user_about_times__range=(begin_time, end_time))
    return render(request, 'operation/user_list.html',
                  {'user_list': user_list, 'user_list_count': len(user_list)})

def user_detail(request, user_id):
    userinfo = User.objects.get(id=user_id)
    borrow_list = Borrow.objects.filter(user=userinfo)
    return render(request, 'operation/user-detail.html', {'userinfo': userinfo, 'borrow_list': borrow_list  })

def change_user(request, user_id):
    name = request.GET.get('name')
    phonenumber = request.GET.get('phonenumber')
    userinfo = User.objects.get(id=user_id)
    userinfo.name = name
    userinfo.phonenumber = phonenumber
    userinfo.save()
    # 重新展示用户相关信息
    borrow_list = Borrow.objects.filter(user=userinfo)
    return render(request, 'userinfo/userinfo-detail.html',
                  {'userinfo': userinfo, 'borrow_list': borrow_list })


def library_list(request):
    booklist = Book.objects.all()
    for book in booklist:
        if book.category.level=='2':
            book.category_name = book.category.top_level.name + ' - ' + book.category.name
        else:
            book.category_name = book.category.name

    return render(request, 'operation/book_list.html',
                  {'booklist': booklist, 'book_list_count': len(booklist)})

def search_library(request):
    begin_time = datetime.datetime(2017, 1, 1) if request.GET['begin_time'] == "" else datetime.datetime(
        *tuple(map(int, request.GET['begin_time'].split('-'))))
    end_time = datetime.date.today() if request.GET['end_time'] == "" else datetime.datetime(
        *tuple(map(int, request.GET['end_time'].split('-'))))
    user_name = request.GET['book_name']
    if user_name == "":
        booklist = Book.objects.filter(add_time__range=(begin_time, end_time))
    else:
        booklist = User.objects.filter(name__icontains=user_name,
                                        add_time__range=(begin_time, end_time))
    return render(request, 'operation/book_list.html',
                  {'booklist': booklist, 'book_list_count': len(booklist)})

def add_library(request):
    if request.method == "GET":
        return render(request, 'operation/add_library.html')
    elif request.method == "POST":
        cover = ''
        if request.FILES.get('file'):
            cover_file = request.FILES['cover']
            cover = 'static/images/covers/' + str(int(time.time())) + str(cover_file)[str(cover_file).index('.')]   # 上传目录及文件名
            save_cover(cover_file, cover)
        else:
            cover = 'static/images/default.jpg'
        Book.objects.create(
            cover = cover,
            *list(request.POST.values())[2:]
        )

def del_library(request, book_id):
    book = Book.objects.get(id=book_id)
    book.delete()
    return HttpResponse(json.dumps({'status': 1}))

def library_detail(request, book_id):
    book = Book.objects.get(id=book_id)
    if book.category.level == '2':
        book.category_name = book.category.top_level.name + ' - ' + book.category.name
    else:
        book.category_name = book.category.name
    borrow_list = Borrow.objects.filter(book=book, status='1')
    return_data = {'book': book, 'borrow_list': borrow_list}
    return render(request, 'operation/library_detail.html', return_data)

def library_change(request, book_id):
    book = Book.objects.get(id=book_id)
    if request.POST.get('cover'):
        cover_file = request.FILES['cover']
        cover = 'static/images/covers/' + str(int(time.time())) + str(cover_file)[
            str(cover_file).index('.')]  # 上传目录及文件名
        save_cover(cover_file, cover)
        book.cover = cover
    for each in list(request.POST.key())[1:].remove('cover'):
        book.each = request.POST.get(each)
    book.save()
    return HttpResponse(json.dumps({'status': 1}) )

def borrow(request, user_id):
    user = User.objects.get(id=user_id)
    bookbill = Book.objects.filter(user=user_id)
    for book in bookbill:
        Borrow.objects.create(book=book.book, user=book.user, )
        book.delete()
    return HttpResponse(json.dumps({'status': 1}))   # 借书成功

def borrow_list(request):
    pass

def return_book(request):

    # for book in booklist:
    #     book.status = 2
    #     book.save()
    pass

def operator_list(request):
    pass

def add_operation(request):
    pass

def del_operation(request):
    pass

def change_operator(request):
    pass

def save_cover(cover_file, filename):
    with open(filename, 'wb+') as f:
        for chunk in cover_file.chunks():
            f.write(chunk)